#include "db.h"

bool Db::openDatabase(QString dbPath)
{
    if (db.isOpen())
    {
        db.removeDatabase(db.connectionName());
        db.close();
    }
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbPath);
    db.open();
    return db.isValid() && db.isOpen();
}

QStringList Db::getTables()
{
    return db.tables(QSql::Tables);
}

QList<QStringList> Db::getResultForTable(QString& tableName)
{
    QString sql("select * from ");
    sql.append(tableName);
    
    QSqlQuery query(sql, db);
    if (query.isActive())
    {
        QList<QStringList> ret;
        
        QSqlRecord records = query.record();
        int colNum = records.count();
        
        QStringList colList;
        for (int i=0; i< colNum;i++)
        {
            colList.append(records.fieldName(i));
        }
        ret.append(colList);
        
        while (query.next())
        {
            QStringList rowData;
            for (int i=0; i< colNum;i++)
            {
                rowData.append(query.value(i).toString());
            }
            ret.append(rowData);
        }
        return ret;
    }else
    {
        return QList<QStringList>();
    }
}
